package com.ciaojian.bytedance.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciaojian.core.enums.business.CouponCodeOriginEnum;
import com.ciaojian.core.enums.business.CouponCodeTakeRecordTypeEnum;
import com.ciaojian.core.enums.business.MemberOrderStatusEnum;
import com.ciaojian.core.enums.business.MemberOrderTypeEnum;
import com.ciaojian.core.factory.ObjectMapperFactory;
import com.ciaojian.core.mapper.CouponCodeMapper;
import com.ciaojian.core.mapper.CouponMapper;
import com.ciaojian.core.mapper.UserMemberMapper;
import com.ciaojian.core.mapper.WorkerInviteMapper;
import com.ciaojian.core.model.*;
import com.ciaojian.core.model.dy.DyOrder;
import com.ciaojian.core.service.CouponCodeService;
import com.ciaojian.core.service.UserMemberService;
import com.ciaojian.core.util.LogUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.time.OffsetDateTime;
import java.util.Date;
import java.util.Map;
import java.util.Optional;

@Service
public class MemberServiceImpl {

    @Resource
    private WorkerInviteMapper workerInviteMapper;
    @Resource
    private UserMemberMapper userMemberMapper;
    @Resource
    private CouponMapper couponMapper;

    public void send(DyOrder dyOrder, Worker worker) throws JsonProcessingException {
        QueryWrapper<MemberDetail> memberDetailQueryWrapper = new QueryWrapper<>();
        memberDetailQueryWrapper.eq("coupon_id",dyOrder.getMemberId());
        // 权益信息
        MemberDetail memberDetail = new MemberDetail().selectOne(memberDetailQueryWrapper);
        dyOrder.setWorkerId(worker.getId());
        dyOrder.setWorkerName(worker.getName());


        Integer isUserMember = checkUserMember(dyOrder.getUserId());
        dyOrder.setIsUserMember(isUserMember);
        // 新增会员订单
        MemberOrder memberOrder = new MemberOrder().setOrderNo(dyOrder.getOrderNo().replace("MD", ""))
                .setUserId(dyOrder.getUserId())
                .setStatus(MemberOrderStatusEnum.paid)
                .setMoney(0L)
                .setMemberId(memberDetail.getMemberId())
                .setInviteId(workerInviteMapper.getWorkerIdByUserId(dyOrder.getUserId()));
        UserMember userMember = new UserMember();
//                    // 如果不是澳宝权益则增加首单优惠
//                    if (!checkAoBao(memberDetail.getId())) {
//                        memberDiscountService.addMemberDiscount(1, order.getUserId());
//                    }
        // 购买的会员卡
        Member memberBuy = new Member().selectById(memberOrder.getMemberId());
        switch (isUserMember) {
            //0开过会员但已过期
            case 0:
                memberOrder.setType(MemberOrderTypeEnum.renew).insert();
                // 对比两种会员卡的折扣谁低
                if (!memberOrder.getMemberId().equals(userMember.getMemberId())) {
                    try {
                        LambdaQueryWrapper<UserMember> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                        lambdaQueryWrapper.eq(UserMember::getUserId, dyOrder.getUserId());
                        userMember = userMember.selectOne(lambdaQueryWrapper);
                        // 拥有的会员卡
                        Member memberOwned = new Member().selectById(userMember.getMemberId());
                        if (memberBuy.getId()==5 && memberOwned.getId()==5) {
                            userMember.setDueDate(DateUtil.offset(new Date(), DateField.YEAR, 1));
                            userMember.setMemberId(memberBuy.getId());
                            userMember.updateById();
                        }else if(memberBuy.getId()!=5){
                            Member member = compareMember(memberBuy, memberOwned);
                            userMember.setDueDate(DateUtil.offset(new Date(), DateField.YEAR, 1));
                            userMember.setMemberId(member.getId());
                            userMember.updateById();
                        }
                    } catch (JsonProcessingException e) {
                        LogUtil.writeErrorLog(e.getMessage());
                        e.printStackTrace();
                    }
                }
                break;
            //-1未开过会员
            case -1:
                memberOrder.setType(MemberOrderTypeEnum.non_renew).insert();

                userMember.setUserId(dyOrder.getUserId());
                userMember.setOrderNo(dyOrder.getOrderNo());
                userMember.setDueDate(DateUtil.offsetMonth(new Date(), 12));
                userMember.setMemberId(memberBuy.getId());
                userMember.insert();
                break;
            //1有效会员
            case 1:
                QueryWrapper<UserMember> userMemberQueryWrapper = new QueryWrapper<>();
                userMemberQueryWrapper.eq("user_id", dyOrder.getUserId());
                userMember = new UserMember().selectOne(userMemberQueryWrapper);
                memberOrder.setType(MemberOrderTypeEnum.renew).insert();
                // 拥有的会员卡
                Member memberOwned = new Member().selectById(userMember.getMemberId());
                if (memberBuy.getId()==5 && memberOwned.getId()==5) {
                    Member member = compareMember(memberBuy, memberOwned);
                    LambdaQueryWrapper<UserMember> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(UserMember::getUserId, dyOrder.getUserId());
                    userMember.setMemberId(member.getId());
                    // 为会员时间延期一年
                    userMember.setDueDate(DateUtil.offset(userMember.getDueDate(), DateField.YEAR, 1)).updateById();
                }else if(memberBuy.getId()!=5){
                    Member member = compareMember(memberBuy, memberOwned);
                    userMember.setDueDate(DateUtil.offset(new Date(), DateField.YEAR, 1));
                    userMember.setMemberId(member.getId());
                    userMember.updateById();
                }
                break;
            default:
        }
        // 给用户发放优惠券
        distributeCode(
                dyOrder.getUserId(),
                memberDetail,
                dyOrder,
                CouponCodeOriginEnum.BUY_MEMBER_DETAIL);
    }
    /**
     * 对照两张会员卡的折扣大小
     *
     * @param v1 /
     * @param v2 /
     * @return 折扣会员卡
     * @throws JsonProcessingException /
     */
    public Member compareMember(Member v1, Member v2) throws JsonProcessingException {
        Map<String, Object> m1 = ObjectMapperFactory.getObjectMapperInstance().readValue(v1.getDiscount(), Map.class);
        Map<String, Object> m2 = ObjectMapperFactory.getObjectMapperInstance().readValue(v2.getDiscount(), Map.class);
        Double d1 = Double.valueOf(m1.get("剪发").toString());
        Double d2 = Double.valueOf(m2.get("剪发").toString());
        return d1.compareTo(d2) < 0 ? v1 : v2;
    }

    /**
     * 发放券码
     *
     * @param userId   发放用户
     * @param optional MemberDetail 的 optional 包装
     * @param order    权益订单
     */
    @Transactional(rollbackFor = Exception.class)
    public void distributeCode(Integer userId,
                               MemberDetail optional,
                               DyOrder order,
                               CouponCodeOriginEnum origin) {
        Integer couponId = optional.getCouponId();

        CouponPackage couponPackage = new CouponPackage().selectById(couponId);

        String coupons = couponPackage.getCoupons();
        String[] codes = coupons.split(",");
        for (String codeId : codes) {
            takes(userId,Integer.parseInt(codeId),null,null);
        }
        order.setStatus(5);
    }

    /**
     * 检查用户是不是会员
     *
     * @param userId 用户的 id
     * @return -1未开过会员 0开过会员但已过期 1有效会员
     */
    public Integer checkUserMember(Integer userId) {
        QueryWrapper<UserMember> userMemberQueryWrapper = new QueryWrapper<>();
        userMemberQueryWrapper.eq("user_id",userId);
        UserMember userMember = userMemberMapper.selectOne(userMemberQueryWrapper);
        // 如果没数据表示从未开过会员
        if (userMember == null) {
            return -1;
        }
        // 如果到期日在当前日之后,返回 1 表示是会员;0 表示曾经开过会员但已过期
        return userMember.getDueDate().after(new Date()) ? 1 : 0;
    }

    public void takes(Integer userId, Integer couponId, Integer mid, CouponCodeTakeRecordTypeEnum type) {
        // 给用户新增券
        QueryWrapper<CouponCode> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("coupon_id", couponId)
                .eq("status", 0)
                .isNull("user_id")
                .last("limit 1");
        CouponCode couponCode = new CouponCode().selectOne(queryWrapper);
        Assert.notNull(couponCode, "券码已被抢完");


        couponCode.setStatus(1);
        couponCode.setUserId(userId);
        couponCode.setOrigin(CouponCodeOriginEnum.BUY_MEMBER_DETAIL);
        couponCode.setExpiredTime(couponMapper.getCouponExpiredTimeById(couponId));
        couponCode.updateById();

        // 新增领取记录
        CouponCodeTakeRecord couponCodeTakeRecord = new CouponCodeTakeRecord();
        couponCodeTakeRecord.setUserId(userId);
        couponCodeTakeRecord.setCouponId(couponId);
        couponCodeTakeRecord.setCouponCode(couponCode.getCode());
        couponCodeTakeRecord.setActivityId(mid);
        couponCodeTakeRecord.setType(type);
        couponCodeTakeRecord.setOrigin(CouponCodeOriginEnum.BUY_MEMBER_DETAIL);
        couponCodeTakeRecord.insert();
        // 领取数量 + 1
        couponMapper.addGetNumById(couponId);
    }
}
